#include "cv.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include "decodeqr.h"
#include <cstdlib>

using namespace cv;
using namespace std;

void QR_decode (IplImage* x);
void area (vector<vector<Point> > cont, Mat image);

Mat bingray, frame,edges,dst,img_bw;
//unsigned char mapa[3][3]={'1','2','3','4','5','6','7','8','9'};
RNG rng(12345);
//Mat lines;
IplImage* img;
QrDecoderHandle decoder=qr_decoder_open();
char file[200];
int n =0,i=0,text_size=0;
unsigned char *text=NULL;
char filename[200];








///////////////////////////////////////////////////////////////////////////////////////////
//MAIN
int main(int, char** argv)
{		namedWindow("Binary",CV_WINDOW_AUTOSIZE);
		namedWindow("Edges",CV_WINDOW_AUTOSIZE);
		namedWindow("Camera",CV_WINDOW_AUTOSIZE);
		namedWindow("Lines",CV_WINDOW_AUTOSIZE);
    VideoCapture cap(0); // open the default camera
	  if(!cap.isOpened())  // check if we succeeded
        return -1;
    
    printf("libdecodeqr version %s\n",qr_decoder_version());		
    for(;;)
    {
        cap >> frame; // get a new frame from camera
				//Binarization 
				cvtColor(frame, bingray, CV_BGR2GRAY);
				adaptiveThreshold(bingray,img_bw,255,0,THRESH_BINARY,99,50);				
				imshow("Binary", img_bw);	
				
				//Contours
				vector<vector<Point> > contours;
  				vector<Vec4i> hierarchy;

				findContours(img_bw, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
				area (contours,img_bw);
	
  			



	
				//Canny			
				blur(bingray,edges,Size(3,3));				
				Canny(edges,edges,20,60,3);
				dst=Scalar::all(0);
				frame.copyTo(dst,edges);
			
				
	
					
				

				// Bloque de filtrados
				/*dst.create(frame.size(),frame.type());        
				cvtColor(frame, bingray, CV_BGR2GRAY);
				Mat img_bw=bingray>128;
        imshow("Binary", img_bw);				
				blur(bingray,edges,Size(3,3));				
				Canny(edges,edges,20,60,3);
				dst=Scalar::all(0);
				frame.copyTo(dst,edges);
				imshow("Camera",frame);
				imshow("Edges",dst);*/

				//imshow("Binary", img_bw);				
				imshow("Camera",frame); 
				//imshow("lines",lines);
				imshow("Edges",dst);       
				char key = (char)waitKey(5); //delay N millis, usually long enough to display and capture input
           switch (key) {
        case 'q':
        case 'Q':
        case 27: //escape key
            return 0;
        case ' ': //Save an image
					resize(img_bw, img_bw, Size(), 2, 2);        	
					sprintf(filename,"%sbin%.3d.jpg",argv[1],n++);
        	imwrite(filename,img_bw);
        	cout << "Saved " << filename << endl;
 					sprintf(file,"%sedge%.3d.jpg",argv[1],n++);
					imwrite(file,dst);
					cout << "Saved edges" << file << endl;       	
				break;
        default:
            break;
            }
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
if(text)
    delete [] text;

qr_decoder_close(decoder);    
return 0;
}

/////////////////////////////////////////////////////////////////

//Area selection

void area (vector<vector<Point> > cont, Mat image)
{vector<vector<Point> > contours_poly( cont.size() );
vector<Rect> boundRect( cont.size()+1 );
vector<Point2f>center( cont.size() );
vector<float>radius( cont.size() );
Point2i top(600,600);
Point2i bottom(0,0);
Rect mainRect;
Mat drawing = Mat::zeros( image.size(), CV_8UC3 );
Mat rectgray;
int dx,dy;
for( int i = 0; i < cont.size(); i++ )
	{approxPolyDP( Mat(cont[i]), contours_poly[i], 3, true );
       	boundRect[i] = boundingRect( Mat(contours_poly[i]) );
	minEnclosingCircle( contours_poly[i], center[i], radius[i] );
     	}
for( int i = 0; i< cont.size(); i++ )
	 {dx=boundRect[i].br().x-boundRect[i].tl().x;
	  dy=boundRect[i].br().y-boundRect[i].tl().y;
	  Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
          //drawContours( drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point() );
       	  if (sqrt((dx*dx)+(dy*dy))>20 && sqrt((dx*dx)+(dy*dy))<500) 
	   {if (boundRect[i].tl().x<top.x)
		top.x=boundRect[i].tl().x;
	    if (boundRect[i].tl().y<top.y)
		top.y=boundRect[i].tl().y;
	    if (boundRect[i].br().x>bottom.x)
		bottom.x=boundRect[i].br().x;
	    if (boundRect[i].br().y>bottom.y)
		bottom.y=boundRect[i].br().y;
	    rectangle( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 );
	   }
	 }
	 mainRect.x=top.x;
	 mainRect.y=top.y;
	 mainRect.width=(bottom.x-top.x);
	 mainRect.height=(bottom.y-top.y);
	 namedWindow("Area",CV_WINDOW_AUTOSIZE);
         if ((bottom.x>0) && (bottom.y>0))				
	 {Mat c(frame,mainRect);
	 cvtColor(c, rectgray, CV_BGR2GRAY);
	 Mat bw=rectgray>100;
	 imshow("Area",bw);
	 img = new IplImage(bw);
	 QR_decode(img);
	 }
	 rectangle( drawing, top, bottom, Scalar(100,0,0), 2, 8, 0 );
 	 namedWindow( "Contours", CV_WINDOW_AUTOSIZE );
  	 imshow( "Contours", drawing );
return;
}


//QR DECODING////////////////////////////////////////////////////////////
void QR_decode (IplImage* x)
{
qr_decoder_set_image_buffer(decoder,x);
        if(!qr_decoder_is_busy(decoder))
				{short sz,stat;
            for(sz=25,stat=0;(sz>=3)&&((stat&QR_IMAGEREADER_DECODED)==0);sz-=2)
                stat=qr_decoder_decode(decoder,sz);
				QrCodeHeader header;
            if(qr_decoder_get_header(decoder,&header))
							{
                if(text_size<header.byte_size+1)
									{
                    if(text)
                        delete [] text;
                    text_size=header.byte_size+1;
                    text=new unsigned char[text_size];
	                }
                qr_decoder_get_body(decoder,text,text_size);
                printf("%s\n\n",text);
							}
					}

return;
}
